package cn.xiuxius.embedded.runconfig;

import cn.xiuxius.embedded.runconfig.ui.*;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.util.ui.FormBuilder;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.util.EnumMap;
import java.util.Map;

public class EasySTCSettingsEditor extends SettingsEditor<EasySTCRunConfiguration> {
    private final JComboBox<EasySTCTask> taskComboBox = new ComboBox<>(EasySTCTask.values());
    private final Map<EasySTCTask, TaskSettingsPanel> panels = new EnumMap<>(EasySTCTask.class);
    private final JPanel cardPanel = new JPanel(new CardLayout());
    private final JPanel mainPanel;

    public EasySTCSettingsEditor() {
        panels.put(EasySTCTask.BUILD, new BuildTaskPanel());
        panels.put(EasySTCTask.RUN, new RunTaskPanel());
        panels.put(EasySTCTask.FLASH, new FlashTaskPanel());
        panels.put(EasySTCTask.ADV_FLASH, new AdvFlashTaskPanel());
        panels.put(EasySTCTask.CLEAN, new EmptyPanel());

        for (var entry : panels.entrySet()) {
            cardPanel.add(entry.getValue().getComponent(), entry.getKey().name());
        }

        taskComboBox.addActionListener(e -> {
            EasySTCTask selected = (EasySTCTask) taskComboBox.getSelectedItem();
            ((CardLayout) cardPanel.getLayout()).show(cardPanel, selected.name());
        });

        mainPanel = FormBuilder.createFormBuilder()
                .addLabeledComponent("Task:", taskComboBox)
                .addComponent(cardPanel)
                .getPanel();
    }

    @Override
    protected void resetEditorFrom(@NotNull EasySTCRunConfiguration config) {
        EasySTCTask task = config.getTask();
        taskComboBox.setSelectedItem(task);
        panels.get(task).resetFrom(config.getOptions());
        ((CardLayout) cardPanel.getLayout()).show(cardPanel, task.name());
    }

    @Override
    protected void applyEditorTo(@NotNull EasySTCRunConfiguration config) {
        EasySTCTask task = (EasySTCTask) taskComboBox.getSelectedItem();
        config.setTask(task);
        panels.get(task).applyTo(config.getOptions());
    }

    @Override
    protected @NotNull JComponent createEditor() {
        return mainPanel;
    }
}
